import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/attend_record/attend_record_calendar/attend_record_calendar_page.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_index/bean/check_in_record_index_group_info_response_bean.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_index/check_in_record_index_page.dart';
import 'package:e_reception_flutter/ui/check_in_record/check_in_record_index/check_in_record_index_view_model.dart';
import 'package:e_reception_flutter/ui/mark/matching_mark_list/matching_mark_list_page.dart';
import 'package:e_reception_flutter/ui/mark/matching_or_mark/bean/mark_info_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';

import 'bean/check_in_record_by_type_list_response_bean.dart';
import 'check_in_record_by_type_list_view_model.dart';

/// 根据类型显示打卡记录列表（用于打卡记录首页）
///
/// @author: zengxiangxi
/// @createTime: 1/9/21 9:37 AM
/// @specialDemand:
class CheckInRecordByTypeListWidget extends StatefulWidget {
  final GroupInfoBean groupInfoBean;
  final String hsn;

  const CheckInRecordByTypeListWidget({Key key, this.groupInfoBean, this.hsn})
      : super(key: key);

  @override
  CheckInRecordByTypeListWidgetState createState() =>
      CheckInRecordByTypeListWidgetState();
}

class CheckInRecordByTypeListWidgetState extends BasePagerState<
        CheckInRecordByTypeListItemBean, CheckInRecordByTypeListWidget>
    with AutomaticKeepAliveClientMixin, VgPlaceHolderStatusMixin {
  CheckInRecordByTypeListViewModel _viewModel;

  StreamSubscription _streamSubscription;

  @override
  void initState() {
    super.initState();
    _viewModel = CheckInRecordByTypeListViewModel(
      this,
      widget?.groupInfoBean,
    );
    _viewModel?.refresh();
    _streamSubscription = CheckInRecordIndexPageState.of(context)
        .multiRefreshStreamController
        ?.stream
        ?.listen((event) {
      _viewModel?.refreshMultiPage();
    });
  }

  @override
  dispose() {
    _streamSubscription?.cancel();
    super.dispose();
  }

  getHsn() {
    return widget?.hsn;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      child: MixinPlaceHolderStatusWidget(
          emptyOnClick: () => _viewModel?.refresh(),
          errorOnClick: () => _viewModel?.refresh(),
          child: Column(
            children: <Widget>[
              _toTopTitleWidget(),
              Expanded(child: _toPullRefreshWidget()),
            ],
          )),
    );
  }

  Widget _toPullRefreshWidget() {
    return VgPullRefreshWidget.bind(
        viewModel: _viewModel, state: this, child: _toListWidget());
  }

  Widget _toListWidget() {
    return ListView.separated(
        itemCount: data?.length ?? 0,
        padding: const EdgeInsets.all(0),
        physics: BouncingScrollPhysics(),
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        itemBuilder: (BuildContext context, int index) {
          return _toListItemWidget(data?.elementAt(index));
        },
        separatorBuilder: (BuildContext context, int index) {
          return SizedBox(
            height: 0,
          );
        });
  }

  Widget _toTopTitleWidget() {
    if (VgToolUtils.isVisitorGroup(
        widget?.groupInfoBean?.groupid, widget?.groupInfoBean?.groupName)) {
      return Container();
    }
    if (data == null || data.isEmpty) {
      return Container();
    }
    return ValueListenableBuilder(
      valueListenable: _viewModel?.infoValueNotifier,
      builder: (BuildContext context, CheckInRecordByTypeListDataBean infoBean,
          Widget child) {
        return Container(
          alignment: Alignment.centerLeft,
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 4),
          child: Text(
            "当前组共${showOriginEmptyStr(infoBean?.groupPerson) ?? 0}人，今日产生记录${infoBean?.todayPerson ?? 0}人${showOriginEmptyStr(infoBean?.todayRecordCnt) ?? 0}次",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: ThemeRepository.getInstance()
                  .getTextMainColor_D0E0F7()
                  .withOpacity(0.6),
              fontSize: 12,
            ),
          ),
        );
      },
    );
  }

  Widget _toListItemWidget(CheckInRecordByTypeListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        if (itemBean == null) {
          return;
        }
        if (itemBean.isUnknow()) {
          bool result = await MatchingMarkListPage.navigatorPush(
              context,
              MarkInfoBean(
                picurl: itemBean?.napicurl,
                fid: itemBean?.fid,
              ));
          if (result ?? false) {
            CheckInRecordIndexPageState.of(context)
                .multiRefreshStreamController
                ?.add(null);
          }
          return;
        }
        // PersonDetailPage.navigatorPush(context, itemBean?.signFuid);
        AttendRecordCalendarPage.navigatorPush(context,itemBean?.signFuid);
      },
      child: Container(
        height: 60,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: _toMainRowWidget(itemBean),
      ),
    );
  }

  Widget _toMainRowWidget(CheckInRecordByTypeListItemBean itemBean) {
    return Row(
      children: <Widget>[
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            VgPhotoPreview.single(
                context,
                showOriginEmptyStr(itemBean?.putpicurl) ??
                    (itemBean?.napicurl ?? ""),
                loadingImageQualityType: ImageQualityType.middleDown);
          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Container(
              height: 36,
              width: 36,
              child: VgCacheNetWorkImage(
                showOriginEmptyStr(itemBean?.putpicurl) ??
                    (itemBean?.napicurl ?? ""),
                fit: BoxFit.cover,
                imageQualityType: ImageQualityType.middleDown,
                defaultErrorType: ImageErrorType.head,
                defaultPlaceType: ImagePlaceType.head,
              ),
            ),
          ),
        ),
        SizedBox(
          width: 9,
        ),
        Expanded(
          child: Container(
            height: 36,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Text(
                      (itemBean?.isUnknow() ?? false)
                          ? "未知"
                          : showOriginEmptyStr(itemBean?.name),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: (itemBean?.isUnknow() ?? false)
                              ? ThemeRepository.getInstance()
                                  .getMinorRedColor_F95355()
                              : ThemeRepository.getInstance()
                                  .getTextMainColor_D0E0F7(),
                          fontSize: 15,
                          height: 1.2),
                    ),
                    Spacer(),
                    // if (!(itemBean?.isUnknow() ?? false))
                    //   Text(
                    //     "${itemBean?.temperature ?? "0.0"}℃",
                    //     maxLines: 1,
                    //     overflow: TextOverflow.ellipsis,
                    //     style: TextStyle(
                    //         color: VgColors.INPUT_BG_COLOR,
                    //         fontSize: 12,
                    //         height: 1.2),
                    //   )
                  ],
                ),
                Builder(
                  builder: (BuildContext context) {
                    final String diffStr = VgToolUtils.getDifferenceTimeStr(
                        itemBean?.maxtime, itemBean?.mintime);
                    return Row(
                      children: <Widget>[
                        Text(
                          VgToolUtils.isShowMaxTime(
                                  itemBean?.mintime, itemBean?.maxtime)
                              ? "${VgToolUtils.getTwoSplitStr(VgToolUtils.getHourAndMinuteStr(itemBean?.mintime), VgToolUtils.getHourAndMinuteStr(itemBean?.maxtime), split: " 至 ")}"
                              : "${VgToolUtils.getHourAndMinuteStr(itemBean?.mintime)}",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: VgColors.INPUT_BG_COLOR,
                              fontSize: 12,
                              height: 1.2),
                        ),
                        Spacer(),
                        if (!(itemBean?.isUnknow() ?? false))
                          Offstage(
                            offstage: diffStr == null || diffStr == "",
                            child: Padding(
                              padding: const EdgeInsets.only(top: 0),
                              child: Icon(
                                Icons.access_time,
                                color: VgColors.INPUT_BG_COLOR,
                                size: 12,
                              ),
                            ),
                          ),
                        if (!(itemBean?.isUnknow() ?? false))
                          SizedBox(
                            width: 4,
                          ),
                        if (!(itemBean?.isUnknow() ?? false))
                          Text(
                            "${diffStr ?? ""}",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                color: VgColors.INPUT_BG_COLOR,
                                fontSize: 12,
                                height: 1.1),
                          )
                      ],
                    );
                  },
                )
              ],
            ),
          ),
        ),
        if (itemBean?.isUnknow() ?? false)
          Container(
            width: 60,
            height: 28,
            margin: const EdgeInsets.only(left: 15),
            decoration: BoxDecoration(
              border: Border.all(color: VgColors.INPUT_BG_COLOR, width: 0.5),
              borderRadius: BorderRadius.circular(14),
            ),
            child: Center(
              child: Text(
                "标记",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 13,
                ),
              ),
            ),
          ),
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void setListData(List<CheckInRecordByTypeListItemBean> list) {
    // print("过滤前：${list?.length ?? 0}");
    // if(list != null && list.isNotEmpty){
    //   list = list.toSet().toSet()?.toList();
    // }
    // print("过滤后：${list?.length ?? 0}");

    super.setListData(list);
  }
}
